package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {

        // 先向下转型以获得刚刚前台传过来的信息
        CreateOrderContext orderContext = (CreateOrderContext) context;
        // 获得前台传来的订单中的商品信息(可能有多个商品)
        List<CartProductDto> cartProductDtoList = orderContext.getCartProductDtoList();
        // 将从上一步获得的商品信息中的商品id放入buyProductIds,以便等下减少库存
        List<Long> buyProductIds = new ArrayList<>();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            buyProductIds.add(cartProductDto.getProductId());
        }
        // 进行排序
        buyProductIds.sort(Long::compareTo);
        // 根据id查询商品库存
        List<Stock> stocksForUpdate = stockMapper.findStocksForUpdate(buyProductIds);
        // 如果没有获得商品库存信息,说明所有商品库存没有初始化
        if (CollectionUtils.isEmpty(stocksForUpdate)) {
            throw new BizException(OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getCode(), OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }
        // 如果商品id个数与查出来的商品库存信息的个数不同,说明有部分商品信息没有初始化
        if (stocksForUpdate.size() != buyProductIds.size()) {
            throw new BizException(OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getCode(), OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }

        // 判断完后开始进行库存减少
        for (CartProductDto cartProductDto : cartProductDtoList) {
            @NotNull @Min(0) Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();
            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);
            stockMapper.updateStock(stock);
        }
        return true;
    }
}